<?php

declare(strict_types=1);

namespace app\model;

use think\facade\Db;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property string $dateymd 日期
 * @property int $supplier_id
 * @property int $agent_id
 * @property int $channel_id
 * @property bool $goods_type 1慢充 2 快充
 * @property int $success 成功数量
 * @property int $fail 失败
 * @property int $cost_time 耗时单位秒
 * @property bool $isp_type 1移动 2联通3电信
 * @property string $created_at
 * @property string $updated_at
 */
class MobileRechargeStatistics extends CommonModel
{
    public $ispType = [
        1 => '移动',
        2 => '联通',
        3 => '电信',
    ];

    /*
    更新统计数据
    order 订单数据
    datetime 发生时间，充值成功或者失败时间
    notifyType  success 充值成功 fail 充值失败

    */
    public function afterNotify($order, $datetime, $notifyType)
    {
        $dataymd = substr($datetime, 0, 10);
        $ispType = getMobileIsp($order['mobile']);

        $uniKey = uncamelize('MobileRechargeStatistics').$dataymd
                    .'_'.$order['supplier_id'].'_'.$order['channel_id']
                    .'_'.$order['order_type'].'_'.$ispType;

        if (!cache($uniKey)) {
            $supplierId = $order['supplier_id'];
            $agentId = $order['agent_id'];
            $channelId = $order['channel_id'];
            $goodsType = $order['order_type'];
            // 先入库数据  在做update
            $sql = <<<sql
            insert ignore into {$this->table} (dateymd,supplier_id,agent_id,agent_id,goods_type,isp_typ) values ('{$dataymd}',{$supplierId},{$agentId},{$channelId},{$goodsType},{$ispType})
sql;
            Db::execute($sql);
            cache($uniKey, 1);
        }

        $where = [
            ['dateymd', $dataymd],
            ['supplier_id', $order['supplier_id']],
            ['agent_id', $order['order_type']],
            ['goods_type', $order['agent_id']],
            ['isp_typ', $ispType],
        ];

        $query = Db::table($this->table)->where($where);
        $timeCost = strtotime($datetime) - $order['supplier_order_create_time'];
        if ('fail' == $notifyType) {
            $res = $query->inc('fail')->inc('time_cost', $timeCost);
        } else {
            $res = $query->inc('success')->inc('time_cost', $timeCost);
        }

        if (!$res) { // 更新不成功加入警报
            doWarning('更新话费充值成功率表失败，更新数量：'.$res);
        }

        return $res;
    }
}
